export const addressResolve = (text, regionTree) => {
  try {
    let { region, address } = regionResolve(text, regionTree);
    if (region.length == 0) {
      return null;
    }
    address = address.replace(/([\u4e00-\u9fa5]+[ ]?[：:])/g, ',');
    let mobile = (address.match(/(\b1[0-9]{10}\b)/g) || [])[0];
    if (!mobile) {
      mobile = (address.match(/(\b[0-9]{8}\b)|(\b[0-9-]{10,16}\b)/g) || [])[0];
    }

    let arr = address
      .replace(mobile ?? '', ',')
      .replace(/([,，\r\n（）：])/g, ',')
      .split(',');
    let fullName = arr
      .filter(a => a.length > 0)
      .orderBy(a => a.length, false)[0]
      .trim();

    if (!/^[\u4e00-\u9fa5]{2,4}$/.test(fullName)) {
      fullName = '';
    }
    address = arr.join('').replace(fullName, '').trim();
    return { fullName, mobile, region, address };
  } catch (e) {
    console.error(e);
    return null;
  }
};

const regionResolve = (text, regionTree) => {
  const reg = /.+?(省|市|自治区|自治州|县|区)/g;
  const region = [];
  const regionName = text.match(reg);
  if (!regionName)
    return {
      address: text,
      region: []
    };

  if (regionName.length == 3) {
    let province = regionTree.find(a => a.name.includes(regionName[0]) || regionName[0].includes(a.name));
    region.push(province.name);
    text = text.replace(province.name, '');
    let city = province.children.find(a => a.name.includes(regionName[1]) || regionName[1].includes(a.name));
    text = text.replace(city.name, '');
    region.push(city.name);
    if (city.children) {
      let area = city.children.find(a => a.name.includes(regionName[2]) || regionName[2].includes(a.name));
      region.push(area.name);
      text = text.replace(area.name, '');
    }
  } else if (regionName.length == 2) {
    let city = regionTree.flatMap(a => a.children).find(a => a.name.includes(regionName[0]) || regionName[0].includes(a.name));
    let area = city.children?.find(a => a.name.includes(regionName[1]) || regionName[1].includes(a.name));
    let province = regionTree.find(a => city.name.startsWith(a.name.substring(0, 2)));

    // address.replace()
    // address.replace()
    if (province) {
      region.push(province.name);
      region.push(city.name);
      if (area) region.push(area.name);
    }
  }
  if (regionName.length == 1) {
    let area, city, province;

    try {
      regionTree.forEach(p => {
        p.children.forEach(c => {
          if (!c.children) return;
          c.children.forEach(a => {
            if (a.name.includes(regionName[0]) || regionName[0].includes(a.name)) {
              province = p;
              area = a;
              city = c;
              text = text.replace(a.name, '');
              throw new Error('跳出循环');
            }
          });
        });
      });
    } catch (e) {
      console.info(e);
    }

    if (province) {
      region.push(province.name);
      region.push(city.name);
      region.push(area.name);
    }
  }
  return {
    region,
    address: text
  };
};
